package com.mi.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import com.mi.dao.BrandDao;
import com.mi.dao.PhoneDao;
import com.mi.entity.Phone;
import com.mi.entity.Phonebrand;
import com.mi.service.BrandService;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * 跟手机品牌有关的service
 * @author muchengxiang
 *
 */
@Service
public class BrandServiceImpl implements BrandService{

	@Resource
	private BrandDao brandDao;
	
	@Resource
	private PhoneDao phoneDao;
	
	/**
	 * 调用dao查询主页所需要的数据，所有品牌，所有品牌的的手机，销量前五的，评论量前十的
	 */
	@Override
	public Map<String, Object> getAllBrand() {
		List<Phonebrand> allBrand = brandDao.getAllBrand();
		List<Phone> salesTop5 = phoneDao.getSalesTop5();
		List<Phone> commentTop10 = phoneDao.getCommentNumTop10();
		Map<String, Object> map=new HashMap<>();
		map.put("allBrand", allBrand);
		map.put("salesTop5", salesTop5);
		map.put("commentTop10", commentTop10);
		return map;
	}

	/**
	 * 根据手机品牌获得所有手机，然后放入值栈，以及在值栈中放入手机品牌
	 */
	@Override
	public void getByBrand(String brandName) {
		List<Phonebrand> byName = brandDao.getByName(brandName);
		Set<Phone> phones = byName.get(0).getPhones();
		int dataSize = phones.size();
		int rows=0;
		if (dataSize%5==0) {
			rows=dataSize/5;
		}else {
			rows=dataSize/5+1;
		}
		//将数据转化为List<List<Phone>>类型
		List<List<Phone>> phoneList=new ArrayList<>();
		List<Phone> rowPhone=new ArrayList<>();
		int index=0;
		int rowIndex=1;
		for (Phone phone : phones) {
			rowPhone.add(phone);
			//代表该换行了就往phoneList添加一行手机
			if (index!=0&&(index+1)%5==0) {
				phoneList.add(rowPhone);
				//清空list
				rowPhone=new ArrayList<>();
				//行数+1
				rowIndex++;
				//最后一行的最后一个也往phoneList添加一行手机
			}else if (rows==rowIndex&&index==dataSize-1) {
				phoneList.add(rowPhone);
			}
			index++;
		}
		ValueStack valueStack = ServletActionContext.getContext().getValueStack();
		//该品牌的所有手机
		valueStack.set("brand", phoneList);
		//品牌名字
		valueStack.set("brandName", brandName);
	}

}
